package com.flyduck.manager;

import com.flyduck.common.exception.BusinessException;
import com.flyduck.entity.AppOrder;
import com.flyduck.entity.AppOrderItem;
import com.flyduck.mapper.AppOrderItemMapper;
import com.flyduck.mapper.AppOrderMapper;
import com.flyduck.modules.app.constant.AppConstant;
import com.flyduck.utils.StringUtils;
import com.flyduck.utils.TokenUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * AppOrderManager
 * </p>
 *
 * @author flyduck
 * @since 2024-05-21
 */
@Component
public class AppOrderManager {

    @Resource
    private TokenUtils tokenUtils;
    @Resource
    private AppOrderMapper appOrderMapper;
    @Resource
    private AppSkuStockManager appSkuStockManager;
    @Resource
    private AppOrderItemMapper appOrderItemMapper;

    public AppOrder verifyAppOrderBySn(String sn){
        Long userId = tokenUtils.getCurrentUserId();

        AppOrder appOrder = appOrderMapper.getAppOrderBySn(sn);
        if(appOrder == null){
            throw new BusinessException("订单不存在");
        }
        if (!userId.equals(appOrder.getUserId())) {
            throw new BusinessException("无权限操作该订单");
        }
        return appOrder;
    }

    public AppOrder verifyAppOrderById(Long id){
        Long userId = tokenUtils.getCurrentUserId();

        AppOrder appOrder = appOrderMapper.selectById(id);
        if(appOrder == null){
            throw new BusinessException("订单不存在");
        }
        if (!userId.equals(appOrder.getUserId())) {
            throw new BusinessException("无权限操作该订单");
        }
        return appOrder;
    }

    @Transactional(rollbackFor = Exception.class)
    public void closeOrder(Long orderId, String adminNode, Long userId) {
        AppOrder appOrder = appOrderMapper.selectById(orderId);
        if (appOrder == null) {
            throw new BusinessException("该订单不存在");
        }
        if (userId == null) {
            throw new BusinessException("管理员不能为空");
        }
        if (StringUtils.isBlank(adminNode)) {
            throw new BusinessException("管理员备注不能为空");
        }
        if (AppConstant.OrderStatus.PENDING_PAYMENT.getCode() != appOrder.getOrderStatus()) {
            throw new BusinessException("该订单状态不允许关闭");
        }

        appOrder.setOrderStatus(AppConstant.OrderStatus.CANCELLED.getCode());
        appOrder.setUpdated(LocalDateTime.now());
        appOrder.setAdminNote("管理员：" + userId + "关闭：" + adminNode);
        appOrderMapper.updateById(appOrder);

        //关闭订单后需要释放库存
        List<AppOrderItem> appOrderItemList = appOrderItemMapper.getAppOrderItemListByOrderId(orderId);
        appSkuStockManager.releaseStock(appOrderItemList);
    }
}
